package com.example.feifei.newproject;

import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.example.feifei.utils.BaseNfcActivity;
import com.example.feifei.utils.LogUtils;
import com.example.feifei.utils.ToastUtil;

import java.io.IOException;
import java.util.Arrays;

/**
 * Created by Administrator on 2018\7\11 0011.
 */

public class NFCFuctionActivity extends BaseNfcActivity {

    private String TAG = "NFCFunctionActivity";

    private TextView text_nfcContent;

    byte a[]={(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff};


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc);
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        ifNFCUse();
        initView();
    }



    private void initView() {
        text_nfcContent = (TextView) findViewById(R.id.text_nfcContent);
        text_nfcContent.setText("这是NFC获取数据");
        ifNFCUse();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Tag nfcTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        byte[] bytesId = nfcTag.getId();// 获取id数组
        String info=ByteArrayToHexString(bytesId);
        boolean auth = false;
        //读取TAG
        MifareClassic mfc = MifareClassic.get(nfcTag);
        try {
            String metaInfo = "";
            mfc.connect();
            int type = mfc.getType();//获取TAG的类型
            int sectorCount = mfc.getSectorCount();//获取TAG中包含的扇区数
            String typeS = "";
            switch (type) {
                case MifareClassic.TYPE_CLASSIC:
                    typeS = "TYPE_CLASSIC";
                    break;
                case MifareClassic.TYPE_PLUS:
                    typeS = "TYPE_PLUS";
                    break;
                case MifareClassic.TYPE_PRO:
                    typeS = "TYPE_PRO";
                    break;
                case MifareClassic.TYPE_UNKNOWN:
                    typeS = "TYPE_UNKNOWN";
                    break;
            }
            metaInfo += "卡片类型：" + typeS + "\n共" + sectorCount + "个扇区\n共"
                    + mfc.getBlockCount() + "个块\n存储空间: " + mfc.getSize() + "B\n"+"Id标签是"+info+"\n+"+"\n";
            LogUtils.e("得到数据======"+metaInfo);

            mfc.transceive(hex2Bytes("00A4040008A000000333010101"));
            byte[] transceive = mfc.transceive(hex2Bytes("00B2011400"));
            text_nfcContent.setText(bytesToHexString(transceive));
            LogUtils.e("得到卡片号码======"+bytesToHexString(transceive));

//            for (int j = 0; j < sectorCount; j++) {
//                auth = mfc.authenticateSectorWithKeyA(j, a);
//                int bCount;
//                int bIndex;
//                if (auth) {
//                    metaInfo += "Sector " + j + ":验证成功\n";
//                    // 读取扇区中的块
//                    bCount = mfc.getBlockCountInSector(j);
//                    bIndex = mfc.sectorToBlock(j);
//                    for (int i = 0; i < bCount; i++) {
//                        byte[] data = mfc.readBlock(bIndex);
//                        metaInfo += "Block " + bIndex + " : "
//                                + bytesToHexString(data) + "\n";
//                        bIndex++;
//                    }
//                } else {
//                    metaInfo += "Sector " + j + ":验证失败\n";
//                }
//            }
//            text_nfcContent.setText(metaInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        String CardId =ByteArrayToHexString(nfcTag.getId());
//        LogUtils.e("得到了NFC信息========="+CardId);

    }

    //字符序列转换为16进制字符串
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++  ) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    private String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
        String out = ""; for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff; i = (in >> 4) & 0x0f; out += hex[i];
            i = in & 0x0f; out += hex[i];
        }
        return out;
    }

    public static byte[] hex2Bytes(String src){
        byte[] res = new byte[src.length()/2];
        char[] chs = src.toCharArray();
        for(int i=0,c=0; i<chs.length; i+=2,c++){
            res[c] = (byte) (Integer.parseInt(new String(chs,i,2), 16));
        }

        return res;
    }


    /**
     * 检测工作,判断设备的NFC支持情况
     *
     * @return
     */
    protected Boolean ifNFCUse() {
        if (mNfcAdapter == null) {
            ToastUtil.showMessage(this,"设备不支持NFC！");
            return false;
        }
        if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
            ToastUtil.showMessage(this,"请在系统设置中先启用NFC功能！");
            return false;
        }
        return true;
    }
}
